package com.gcpproxy.image;

import com.gcpproxy.config.AppConfig;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 图片处理器
 * 整合图片验证和处理功能
 */
@Component
public class ImageHandler {

    private static final Logger logger = LoggerFactory.getLogger(ImageHandler.class);
    
    private static final Pattern DATA_URI_PATTERN = Pattern.compile("^data:([^;]+);base64,(.+)$");
    private static final Set<String> SUPPORTED_MIME_TYPES = Set.of(
        "image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp", "image/bmp"
    );

    @Autowired
    private AppConfig appConfig;

    /**
     * 处理图片输入，支持多种格式
     */
    public Map<String, Object> processImage(String imageInput) {
        try {
            logger.debug("开始处理图片输入");
            
            if (imageInput == null || imageInput.trim().isEmpty()) {
                throw new IllegalArgumentException("图片输入不能为空");
            }

            // 检查是否为data URI格式
            Matcher matcher = DATA_URI_PATTERN.matcher(imageInput.trim());
            if (matcher.matches()) {
                return processDataUri(matcher.group(1), matcher.group(2));
            }
            
            // 检查是否为URL
            if (imageInput.startsWith("http://") || imageInput.startsWith("https://")) {
                return processImageUrl(imageInput);
            }
            
            // 尝试作为base64字符串处理
            return processBase64String(imageInput);
            
        } catch (Exception e) {
            logger.error("处理图片失败: {}", e.getMessage());
            throw new RuntimeException("图片处理失败: " + e.getMessage(), e);
        }
    }

    /**
     * 处理data URI格式的图片
     */
    private Map<String, Object> processDataUri(String mimeType, String base64Data) {
        logger.debug("处理data URI格式图片 - MIME类型: {}", mimeType);
        
        if (!SUPPORTED_MIME_TYPES.contains(mimeType)) {
            throw new IllegalArgumentException("不支持的图片格式: " + mimeType);
        }

        try {
            byte[] imageData = Base64.getDecoder().decode(base64Data);
            validateImageSize(imageData);
            
            Map<String, Object> result = new HashMap<>();
            result.put("mimeType", mimeType);
            result.put("data", imageData );
            result.put("source", "data_uri");
            result.put("size", imageData.length);
            
            logger.debug("成功处理data URI图片 - 大小: {} bytes", imageData.length);
            return result;
            
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("无效的base64数据", e);
        }
    }

    /**
     * 处理图片URL
     */
    private Map<String, Object> processImageUrl(String imageUrl) {
        logger.debug("处理图片URL: {}", imageUrl);
        
        try {
            URL url = new URL(imageUrl);
            try (InputStream inputStream = url.openStream()) {
                byte[] imageData = IOUtils.toByteArray(inputStream);
                validateImageSize(imageData);
                
                // 尝试从URL推断MIME类型
                String mimeType = guessMimeTypeFromUrl(imageUrl);
                
                Map<String, Object> result = new HashMap<>();
                result.put("mimeType", mimeType);
                result.put("data", imageData );
                result.put("source", "url");
                result.put("url", imageUrl);
                result.put("size", imageData.length);
                
                logger.debug("成功处理URL图片 - 大小: {} bytes", imageData.length);
                return result;
            }
        } catch (IOException e) {
            throw new RuntimeException("无法下载图片: " + imageUrl, e);
        }
    }

    /**
     * 处理base64字符串
     */
    private Map<String, Object> processBase64String(String base64String) {
        logger.debug("处理base64字符串");
        
        try {
            byte[] imageData = Base64.getDecoder().decode(base64String);
            validateImageSize(imageData);
            
            // 尝试检测图片格式
            String mimeType = detectMimeType(imageData);
            
            Map<String, Object> result = new HashMap<>();
            result.put("mimeType", mimeType);
            result.put("data", imageData );
            result.put("source", "base64");
            result.put("size", imageData.length);
            
            logger.debug("成功处理base64图片 - 大小: {} bytes", imageData.length);
            return result;
            
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("无效的base64数据", e);
        }
    }

    /**
     * 验证图片大小
     */
    private void validateImageSize(byte[] imageData) {
        long maxSize = appConfig.getImage().getMaxSize();
        if (imageData.length > maxSize) {
            throw new IllegalArgumentException(
                String.format("图片大小超过限制: %d bytes > %d bytes", imageData.length, maxSize));
        }
        
        if (imageData.length == 0) {
            throw new IllegalArgumentException("图片数据为空");
        }
    }

    /**
     * 从URL推断MIME类型
     */
    private String guessMimeTypeFromUrl(String url) {
        String lowerUrl = url.toLowerCase();
        if (lowerUrl.endsWith(".jpg") || lowerUrl.endsWith(".jpeg")) {
            return "image/jpeg";
        } else if (lowerUrl.endsWith(".png")) {
            return "image/png";
        } else if (lowerUrl.endsWith(".gif")) {
            return "image/gif";
        } else if (lowerUrl.endsWith(".webp")) {
            return "image/webp";
        } else if (lowerUrl.endsWith(".bmp")) {
            return "image/bmp";
        }
        return "image/jpeg"; // 默认
    }

    /**
     * 检测图片的MIME类型
     */
    private String detectMimeType(byte[] imageData) {
        if (imageData.length < 4) {
            return "image/jpeg"; // 默认
        }

        // 检查文件头
        if (imageData[0] == (byte) 0xFF && imageData[1] == (byte) 0xD8) {
            return "image/jpeg";
        } else if (imageData[0] == (byte) 0x89 && imageData[1] == 'P' && 
                   imageData[2] == 'N' && imageData[3] == 'G') {
            return "image/png";
        } else if (imageData[0] == 'G' && imageData[1] == 'I' && imageData[2] == 'F') {
            return "image/gif";
        } else if (imageData.length >= 12 && 
                   imageData[8] == 'W' && imageData[9] == 'E' && 
                   imageData[10] == 'B' && imageData[11] == 'P') {
            return "image/webp";
        } else if (imageData[0] == 'B' && imageData[1] == 'M') {
            return "image/bmp";
        }

        return "image/jpeg"; // 默认
    }

    /**
     * 获取支持的图片格式
     */
    public Set<String> getSupportedFormats() {
        return new HashSet<>(SUPPORTED_MIME_TYPES);
    }
}